package deng.qiya.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.XmlMappingException;

public class XMLConverter {

	private Marshaller marshaller;
	private Unmarshaller unmarshaller;

//	public void convertFromObjectToXML(Object object, String filepath) throws IOException, JAXBException {
//
//		FileOutputStream os = null;
//		try {
//			os = new FileOutputStream(filepath);
//			getMarshaller().marshal(object, new StreamResult(os));
//		} finally {
//			if (os != null) {
//				os.close();
//			}
//		}
//	}
	
	public String convertFromObjectToStringXML(Object object) throws XmlMappingException, IOException{
		
		StringWriter writer = new StringWriter();
		StreamResult result = new StreamResult(writer);

		getMarshaller().marshal(object, result);

		String xmlString = writer.toString();
		
		return xmlString;
	}
	
//	public Object convertFromXMLToObject(String xmlfile) throws IOException, JAXBException {
//
//		FileInputStream is = null;
//		try {
//			is = new FileInputStream(xmlfile);
//			return getUnmarshaller().unmarshal(new StreamSource(is));
//		} finally {
//			if (is != null) {
//				is.close();
//			}
//		}
//	}
	
	public Object convertFromXMLToObject(InputStream stream) throws XmlMappingException, IOException {
		
		return getUnmarshaller().unmarshal(new StreamSource(stream));
	}
	
	public Object convertFromStringXMLObjectToObject(String xml) throws XmlMappingException, IOException{
		return getUnmarshaller().unmarshal(new StreamSource(new StringReader(xml)));
	}

	public Marshaller getMarshaller() {
		return marshaller;
	}

	public void setMarshaller(Marshaller marshaller) {
		this.marshaller = marshaller;
	}

	public Unmarshaller getUnmarshaller() {
		return unmarshaller;
	}

	public void setUnmarshaller(Unmarshaller unmarshaller) {
		this.unmarshaller = unmarshaller;
	}

}
